package com.aliyun;
/**
 * 阿里云OSS上传类
 */

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.AccessControlList;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.util.Calendar;

@Component
@PropertySource("classpath:oss.properties")
public class OssUpload implements InitializingBean {

	private int timeout=5000;
	@Value("${accessKeyId}")
	private  String accessKeyId;

	@Value("${accessKeySecret}")
	private String accessKeySecret;

	@Value("${bucketName}")
	private  String bucketName;

	@Value("${endpoint}")
	private  String ossEndpoint;

	@Value("${url}")
	private  String url;
	
	

	
	private OSSClient ossClient;

	public OssUpload() {
	}

	/**
	 * OSS初始化
	 */
	public void init() {
		ClientConfiguration conf = new ClientConfiguration();
		conf.setConnectionTimeout(timeout);
		conf.setMaxErrorRetry(10);
		ossClient = new OSSClient("http://" + ossEndpoint, accessKeyId, accessKeySecret, conf);
	}
	
	/**
	 * 获取文件的URL地址
	 * @param newFileName
	 * @return
	 */
	public  String getURL(final String newFileName) {
		// TODO Auto-generated method stub
        String url = "";
		AccessControlList accs = ossClient.getBucketAcl(bucketName);
		if (accs.getGrants().isEmpty()) {
			Calendar c = Calendar.getInstance();
			c.add(Calendar.HOUR_OF_DAY, 1);
			URL _url = ossClient.generatePresignedUrl(bucketName, newFileName, c.getTime());
			url = _url.getPath();
		} else {
			url = String.format("%s/%s",this.url, newFileName);
		}
		ossClient.shutdown();

		return url;
	}


	

	public void setBucketName(String bucketName) {
		this.bucketName = bucketName;
	}

	public void destroy() {
		ossClient.shutdown();
	}

	/**
	 * 指定的key是否存在
	 */
	public boolean isExist(String key) {
		key = genKey(key);
		return ossClient.doesObjectExist(bucketName, key);
	}

	/**
	 * 从OSS中获取文件输入流
	 */
	public InputStream getObjeInputStream(String key) {
		key = genKey(key);
		OSSObject obj = ossClient.getObject(bucketName, key);
		return obj.getObjectContent();
	}

	/**
	 * 将输入流下载存到指定的File文件中
	 */
	public void saveIsToFile(InputStream is, File file) {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			byte[] buffer = new byte[1024 * 10];
			int len = -1;
			while ((len = is.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.safeClose(fos);
		}
	}

	/**
	 * 文件下载,以流的形式
	 */
	public void downObj(String key, File file) {
		key = genKey(key);
		InputStream is = getObjeInputStream(key);
		saveIsToFile(is, file);
	}

	/**
	 * 简单上传OSS文件
	 */
	public String upload(final String newFileName, final File uploadName) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				
				ObjectMetadata meta = new ObjectMetadata();
				if (newFileName!=null)
				{
					if (newFileName.endsWith(".png"))
					{
						meta.setContentType("image/png");
					}
					else if (newFileName.endsWith(".jpg"))
					{
						meta.setContentType("image/jpg");
					}
					else if (newFileName.endsWith(".gif"))
					{
						meta.setContentType("image/gif");
					}
					else if (newFileName.endsWith(".apk"))
					{
						meta.setContentType("application/octet-stream");
					}
					else if (newFileName.endsWith(".mp3"))
					{
						meta.setContentType("audio/mp3");
					}
					else if (newFileName.endsWith(".mp4"))
					{
						meta.setContentType("video/mp4");
					}
				}
				
				String ossFile = genKey(newFileName);
				ossClient.putObject(bucketName, ossFile, uploadName, meta);

			}
		}).start();

		return null;
	}

	/**
	 * 删除指定key
	 */
	public void delObj(String key) {
		ossClient.deleteObject(bucketName, key);
	}

	/**
	 * 处理key开头是/,返回开头没有/的key
	 */
	private String genKey(String key) {
		if (key != null) {
			key = key.replaceAll("\\\\", "/");
		}
		while (key != null && key.startsWith("/")) {
			key = key.substring(1, key.length());
		}
		return key;
	}

	public OSSClient getOSSClient() {
		return ossClient;
	}

	public void setAccessKeyId(String accessKeyId) {
		this.accessKeyId = accessKeyId;
	}

	public void setAccessKeySecret(String accessKeySecret) {
		this.accessKeySecret = accessKeySecret;
	}

	public void setOssBucket(String ossBucket) {
		this.bucketName = ossBucket;
	}

	public void setOssEndpoint(String ossEndpoint) {
		this.ossEndpoint = ossEndpoint;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	public void setUrl(String url) {
		this.url = url;
	}
	
	public OSSClient getOssClient() {
		return ossClient;
	}

	public void setOssClient(OSSClient ossClient) {
		this.ossClient = ossClient;
	}

	public String getAccessKeyId() {
		return accessKeyId;
	}

	public String getAccessKeySecret() {
		return accessKeySecret;
	}

	public String getBucketName() {
		return bucketName;
	}

	public String getOssEndpoint() {
		return ossEndpoint;
	}

	public int getTimeout() {
		return timeout;
	}

	public String getUrl() {
		return url;
	}


	@Override
	public void afterPropertiesSet() throws Exception {
		 init();
	}
}
